<template>
  <div v-loading="loading">
    <!-- 用于添加编辑 v-if="$route.query.type == 'add' || $route.query.type == 'edit'" -->
    <div
      class="detail"
      v-if="$route.query.type == 'add' || $route.query.type == 'edit'"
    >
      <div class="flex description">
        <div class="lable">步骤描述</div>
        <el-input
          v-input-restrict
          style="width: 660px"
          v-if="type == 'add' || type == 'edit'"
          maxlength="500"
          show-word-limit
          :autosize="{ minRows: 5, maxRows: 8 }"
          v-model="form.describe"
          type="textarea"
          placeholder="请输入步骤描述"
        />
        <div
          style="width: 600px; white-space: pre-wrap"
          v-else
          v-html="form.describe"
        ></div>
      </div>

      <!-- 教学内容 -->
      <div class="stepbox">
        <div class="stepbox_title">
          <div class="flex">
            教学内容
            <div class="stepbox_tip">
              注：内容可以通过拖拽来调整排序, 双击标题可编辑标题
            </div>
          </div>
          <div style="color: #999999; font-size: 12px; margin-top: -8px">
            视频支持上传AVC(H264)编码的mp4并小于300MB
          </div>
        </div>

        <!-- 环节列表 -->
        <input
          style="display: none"
          class="uploadContain_input"
          type="file"
          accept=".gif, .png, .jpeg,  .jpg,  .mp4, .webm, .pdf, .docx, .doc, .rtf, .pptx, .ppt,  .xls, .xlsx ,.wps ,.ofd
        ,.txt ,.js ,.json ,.css ,.sql ,.xml ,.java ,.cs(c#)"
          ref="fileInput"
          @change="uploadFile($event)"
          multiple
        />
        <div class="stepbox_tabs">
          <el-tabs
            ref="tabs"
            v-model="stepIndex"
            type="card"
            @tab-remove="handleTabsEdit"
          >
            <el-tab-pane
              class-name="alldrop"
              closable
              v-for="(item, index) in form.contentTemporaries"
              :key="index"
              :name="index + ''"
            >
              <template v-slot:label>
                <el-input
                  v-input-restrict
                  clearable
                  ref="contentNameRef"
                  v-if="item.showEdit"
                  @blur="changeContentName(item)"
                  v-model="item.contentName"
                  class="contentName"
                  type="text"
                ></el-input>
                <span
                  v-if="!item.showEdit"
                  @dblclick="changeShowEdit(item, index)"
                  >{{
                    item.contentName ? item.contentName : `内容${index + 1}`
                  }}</span
                >
              </template>
              <div class="tabContent">
                <div class="flex addflies">
                  <div>
                    <div
                      class="addflie flex shou"
                      style="background: #28b28b"
                      @click="uploadType('上传教学课件')"
                    >
                      <img
                        src="@/assets/images/courseadd/upload.png"
                        alt=""
                      />上传附件
                    </div>
                    <div
                      @click="
                        openfile(item1.fileUrl, item1.fileName, item1.type)
                      "
                      class="file flex shou"
                      v-for="(item1, index1) in item.taskFileTemporaries"
                      v-if="item1.type == 1"
                      :key="index1"
                    >
                      <img class="icon" src="@/assets/images/hxz.png" alt="" />
                      <img
                        class="iconactive"
                        src="@/assets/images/lvhxz.png"
                        alt=""
                      />
                      <div class="name overtxt">{{ item1.fileName }}</div>
                      <img
                        @click.stop="delCourseware('三维课件', index1)"
                        class="del"
                        src="@/assets/images/del.png"
                        alt=""
                      />
                    </div>
                  </div>

                  <div style="margin-left: 24px">
                    <div
                      class="addflie flex shou"
                      style="background: #f89a33"
                      @click="uploadType('上传三维课件')"
                    >
                      <img
                        src="@/assets/images/courseadd/upload.png"
                        alt=""
                      />插入元智书
                    </div>
                    <div
                      @click="
                        openfile(item1.fileUrl, item1.fileName, item1.type)
                      "
                      class="file flex shou"
                      v-for="(item1, index1) in item.taskFileTemporaries"
                      v-if="item1.type == 0"
                      :key="index1"
                    >
                      <img class="icon" src="@/assets/images/hxz.png" alt="" />
                      <img
                        class="iconactive"
                        src="@/assets/images/lvhxz.png"
                        alt=""
                      />
                      <div class="name overtxt">{{ item1.fileName }}</div>
                      <img
                        @click.stop="delCourseware('三维课件', index1)"
                        class="del"
                        src="@/assets/images/del.png"
                        alt=""
                      />
                    </div>
                  </div>
                </div>
                <wangEditor
                  :uuid="courseForm.dirName"
                  v-model="item.description"
                  :courseId="courseId"
                  @turnWord="uploadWordToNode($event, item)"
                />
              </div>
            </el-tab-pane>
            <el-tab-pane key="add" name="add" :closable="false">
              <div
                slot="label"
                class="addStep flex shou"
                @click="handleAddStep"
                v-preventReClick
              >
                + 添加教学内容
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <add3DCourse :open.sync="add3DOpen" @refresh="add3DReturn"></add3DCourse>
    </div>
    <!-- 用于查看 和 审核的时候 -->
    <div v-else class="lookDetail">
      <div class="flex item">
        <div class="item_lable">步骤描述</div>
        <div
          v-if="form.describe"
          class="item_value"
          v-html="form.describe"
        ></div>
        <div v-else class="item_value"></div>
      </div>
      <!-- 环节列表 -->
      <div class="steps">
        <el-tabs v-model="stepIndex">
          <el-tab-pane
            v-for="(item, index) in form.contentTemporaries"
            :key="index"
            :name="index + ''"
          >
            <template v-slot:label>
              <span>{{
                item.contentName ? item.contentName : `内容${index + 1}`
              }}</span>
            </template>
            <div
              class="content"
              v-html="item.description"
              style="overflow: auto; white-space: pre-wrap"
            ></div>
            <div
              class="fileTitle"
              v-if="
                item.taskFileTemporaries && item.taskFileTemporaries.length > 0
              "
            >
              教学课件:
            </div>
            <div class="flex files" v-if="item.taskFileTemporaries">
              <div
                class="flex files_file shou"
                @click="openfile(item1.fileUrl, item1.fileName, item1.type)"
                v-for="(item1, index1) in item.taskFileTemporaries"
                :key="index1"
              >
                <img
                  :src="returnIcon(item1.fileUrl, item1.type)"
                  alt=""
                  class="icon"
                />
                <div class="overtxt filename">
                  {{ item1.fileName }}{{ item1.type }}
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 底部按钮用于  -->
    <div class="detailbottom flexbet" style="">
      <div class="flex">
        <!-- 用于添加和编辑 可添加考核和练习 -->
        <div class="flex" v-if="type == 'add' || type == 'edit'">
          <el-tooltip
            class="item"
            effect="dark"
            content="练习非强制完成，不影响员工学习下一内容"
            placement="top-start"
          >
            <div
              @click.stop="
                handleAddPractice(
                  {
                    practiceId: form.practiceId,
                    practicePublish: form.practicePublish,
                  },
                  taskId
                )
              "
              :class="[
                form.practiceId && form.practicePublish
                  ? 'examBtn'
                  : 'noExamBtn',
                'flex',
                'rela',
                'shou',
              ]"
            >
              <img
                class="activeIcon"
                src="@/assets/images/courseadd/activeAdd.png"
                alt=""
              />
              <img
                class="icon"
                src="@/assets/images/courseadd/add.png"
                alt=""
              />习题练习
              <img
                @click.stop="handleDelPractice(taskId)"
                class="abso del"
                src="@/assets/images/close.png"
                alt=""
              />
            </div>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="作业强制完成，不通过可以直接重做，成绩合格后员工方可学习下一内容"
            placement="top-start"
          >
            <div
              @click.stop="
                handleAddHomework(
                  {
                    practiceId: form.homeworkId,
                    practicePublish: form.homeworkPublish,
                  },
                  taskId
                )
              "
              :class="[
                form.homeworkId && form.homeworkPublish
                  ? 'examBtn'
                  : 'noExamBtn',
                'flex',
                'rela',
                'shou',
              ]"
            >
              <img
                class="activeIcon"
                src="@/assets/images/courseadd/activeAdd.png"
                alt=""
              />
              <img
                class="icon"
                src="@/assets/images/courseadd/add.png"
                alt=""
              />作业
              <img
                @click.stop="handleDelHomework(taskId)"
                class="abso del"
                src="@/assets/images/close.png"
                alt=""
              /></div
          ></el-tooltip>
          <!-- 考核按钮 examPublish 0未发布 1已发布-->
          <el-tooltip
            class="item"
            effect="dark"
            content="考核强制完成，不通需要申请补考，成绩合格后员工方可学习下一内容"
            placement="top-start"
          >
            <div
              @click.stop="
                handleAddExam(
                  { examId: form.examId, examPublish: form.examPublish },
                  taskId
                )
              "
              :class="[
                form.examId && form.examPublish === 1 ? 'examBtn' : 'noExamBtn',
                'flex',
                'rela',
                'shou',
              ]"
            >
              <img
                class="activeIcon"
                src="@/assets/images/courseadd/activeAdd.png"
                alt=""
              />
              <img
                class="icon"
                src="@/assets/images/courseadd/add.png"
                alt=""
              />考核
              <img
                @click.stop="handleDelExam(taskId)"
                class="abso del"
                src="@/assets/images/close.png"
                alt=""
              /></div
          ></el-tooltip>
        </div>
        <!-- 用于审核和查看时候显示 考核按钮 -->
        <div class="flex" v-if="type !== 'add' && type !== 'edit'">
          <!-- 习题练习 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="练习非强制完成，不影响员工学习下一内容"
            placement="top-start"
          >
            <div
              @click.stop="
                type !== 'add' &&
                type !== 'edit' &&
                JSON.stringify($store.getters.roles) !==
                  JSON.stringify(['user', 'sa'])
                  ? handleAddPractice(
                      {
                        practiceId: form.practiceId,
                        practicePublish: form.practicePublish,
                      },
                      taskId,
                      'look'
                    )
                  : ''
              "
              v-if="
                ($route.query.status == 'course' && form.practiceId) ||
                (form.practiceId && form.practicePublish == 1)
              "
              :class="[
                'examBtn',
                'flex',
                'rela',
                type !== 'add' &&
                type !== 'edit' &&
                JSON.stringify($store.getters.roles) !==
                  JSON.stringify(['user', 'sa'])
                  ? 'shou'
                  : '',
              ]"
            >
              <img
                class="icon"
                src="@/assets/images/courseadd/add.png"
                alt=""
              />习题练习
            </div>
          </el-tooltip>
          <!-- 作业 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="作业强制完成，不通过可以直接重做，成绩合格后员工方可学习下一内容"
            placement="top-start"
          >
            <div
              @click.stop="
                type !== 'add' &&
                type !== 'edit' &&
                JSON.stringify($store.getters.roles) !==
                  JSON.stringify(['user', 'sa'])
                  ? handleAddHomework(
                      {
                        practiceId: form.homeworkId,
                        practicePublish: form.homeworkPublish,
                      },
                      taskId,
                      'look'
                    )
                  : ''
              "
              v-if="
                ($route.query.status == 'course' && form.homeworkId) ||
                (form.homeworkId && form.homeworkPublish == 1)
              "
              :class="[
                'examBtn',
                'flex',
                'rela',
                type !== 'add' &&
                type !== 'edit' &&
                JSON.stringify($store.getters.roles) !==
                  JSON.stringify(['user', 'sa'])
                  ? 'shou'
                  : '',
              ]"
            >
              <img
                class="icon"
                src="@/assets/images/courseadd/add.png"
                alt=""
              />作业
            </div>
          </el-tooltip>
          <!-- 考核按钮 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="考核强制完成，不通需要申请补考，成绩合格后员工方可学习下一内容"
            placement="top-start"
          >
            <div
              @click.stop="
                type !== 'add' &&
                type !== 'edit' &&
                JSON.stringify($store.getters.roles) !==
                  JSON.stringify(['user', 'sa'])
                  ? handleAddExam(
                      { examId: form.examId, examPublish: form.examPublish },
                      taskId,
                      'look'
                    )
                  : ''
              "
              v-if="
                ($route.query.status == 'course' && form.examId) ||
                (form.examId && form.examPublish == 1)
              "
              :class="[
                'examBtn',
                'flex',
                'rela',
                type !== 'add' &&
                type !== 'edit' &&
                JSON.stringify($store.getters.roles) !==
                  JSON.stringify(['user', 'sa'])
                  ? 'shou'
                  : '',
              ]"
            >
              <img
                class="icon"
                src="@/assets/images/courseadd/add.png"
                alt=""
              />考核
            </div>
          </el-tooltip>
        </div>
      </div>
      <div class="flex">
        <el-button
          v-preventReClick
          v-if="type == 'add' || type == 'edit'"
          type="primary"
          @click="handleSubmitForm()"
          >保 存</el-button
        >
        <el-button
          v-preventReClick
          v-if="type == 'audit' || type == 'detail'"
          type="primary"
          @click="cancel"
          >退 出</el-button
        >
      </div>
    </div>
    <fileDrawer
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :type="drawertype"
      :isHttps="isHttps"
    ></fileDrawer>
    <!-- 添加考试 -->
    <examDialog
      ref="examDialog"
      port="teacher"
      :lookState="lookState"
      :topicCategoryId="topicCategoryId"
      :isOfflineExam="isOfflineExam"
      :operationType="exam_type"
      :paperOpen.sync="exam_paperOpen"
      :rowId="exam_examId"
      :taskld="exam_taskId"
      @refresh="examDialogReturn"
    ></examDialog>
    <!-- 题库 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="选择试题"
      :visible.sync="question_open"
      width="70vw"
      append-to-body
    >
      <div class="topicListDiv">
        <TopicList
          :parentopen="question_open"
          ref="myTopicList"
          :propsCategoryId="topicCategoryId"
          :hiddenEdit="true"
          :hideAdd="true"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import fileDrawer from "@/components/fileDrawer.vue";
import TopicList from "./TopicList";
import examDialog from "./examDialog";
import wangEditor from "@/components/wangEditor.vue";
import add3DCourse from "./add3DCourse";
import Sortable from "sortablejs";
import { fammterString, uploadOSS } from "@/api/upload";
import {
  sort_courseTaskContent,
  getPost_courseTask,
  updatePost_courseTask,
  listPost_courseTaskContent,
  addPost_courseTaskContent,
  delPost_courseTaskContent,
  addPost_file,
  delPost_file,
  listPost_file,
} from "@/api/course/task";
import {
  getPost_officalCourseTask,
  listPost_officalCourseTaskContent,
  updateContentTemporary,
  listPost_officalFile,
} from "@/api/course/officalTask";
import questionMixin from "../questionMixin";
import { returnIcon } from "@/utils/util";
export default {
  mixins: [questionMixin],
  components: { add3DCourse, wangEditor, TopicList, examDialog, fileDrawer },
  props: {
    type: String,
    taskId: [String, Number],
    courseId: [String, Number],
    topicCategoryId: {},
    courseForm: [Object],
    tabIndex: [String, Number],
  },
  data() {
    return {
      sortArr: [],
      exam_paperOpen: false,
      isHttps: false,
      lookState: false,
      isOfflineExam: false,
      queryParam: "",
      isLock: false,
      loading: false,
      // 文件组件弹框
      drawer: false,
      drawerurl: "",
      drawername: "",
      drawertype: "",
      returnIcon: function (url, type) {
        return returnIcon(url, type);
      },
      // 版本号
      version: "3.4.0",
      content: "",
      stepIndex: "0",
      // 表单参数
      //   文件类型 0：3d 1:不是3d
      form: {
        taskId: undefined,
        taskName: undefined,
        describe: undefined,
        contentTemporaries: [],
      },
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "步骤名称不能为空", trigger: "blur" },
        ],
      },
      //   上传分类型
      utype: "",
      //   添加3d课件弹窗
      add3DOpen: false,
    };
  },
  created() {
    this.queryParam = this.$route.query;
  },
  beforeDestroy() {
    if (this.tabIndex == 1) {
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        if (this.form.id) {
          console.log("切换到任务");
          let form = this.form;
          this.submitForm(form);
        }
      }
    }
  },
  watch: {
    //监听form.id   来判断同组件切换时   保存上一个内容
    form: {
      handler(newValue, oldValue) {
        //判断有旧的form.id   说明是同组件切换   没有则证明是初次加载该组件
        if (oldValue.id) {
          //判断有旧的form.id  是否变化   有变化说明是组件切换了数据  将旧的id数据保存
          if (oldValue.id != newValue.id) {
            if (this.tabIndex == 1) {
              if (
                this.$route.query.type == "add" ||
                this.$route.query.type == "edit"
              ) {
                console.log("来判断同组件切换时", oldValue);
                this.submitForm(oldValue);
              }
            }
          }
        }
      },
    },
    stepIndex(newValue, oldValue) {
      console.log(this.stepIndex, newValue, oldValue);
      if (this.$route.query.type == "add" || this.$route.query.type == "edit") {
        if (oldValue != "add") {
          this.updateContentTemporary(newValue, oldValue);
        }
      }
      if (newValue != "add") {
        // 获取附件列表
        this.getFileList();
      }
      const videos = document.querySelectorAll("video");
      if (videos && videos.length > 0) {
        videos.forEach((video) => {
          video.pause();
        });
      }
    },
    taskId: {
      handler(newValue, oldValue) {
        this.stepIndex = "0";
        this.getInfo();
      },
      immediate: true,
    },
  },
  methods: {
    examDialogReturn(exam) {
      // 是考核
      if (this.exam_type == 2 || this.exam_type == 1) {
        this.form.examPublish = exam.publish;
      }
      // 是作业
      if (this.exam_type == 7 || this.exam_type == 8) {
        this.form.homeworkPublish = exam.publish;
      }
      // 是练习
      else {
        this.form.practicePublish = exam.publish;
      }
      console.log(exam, this.exam_type, this.form);
    },
    async updateContentTemporary(newValue, oldValue) {
      if (!this.form.contentTemporaries[oldValue]) {
        return;
      }
      if (
        this.form.contentTemporaries &&
        this.form.contentTemporaries.length > 0
      ) {
        let params = this.form.contentTemporaries[oldValue];
        delete params.sort;
        let res = await updateContentTemporary(params);
      }
    },
    uploadWordToNode(formData, item) {
      item.description += formData;
    },
    changeShowEdit(item) {
      item.showEdit = true;
      this.$nextTick(() => {
        this.$refs["contentNameRef"][0].focus();
      });
      console.log(
        item.showEdit,
        "form.contentTemporaries",
        this.form.contentTemporaries
      );
    },
    changeContentName(item) {
      item.showEdit = false;
      console.log(
        item.contentName,
        "form.contentTemporaries",
        this.form.contentTemporaries
      );
    },
    /* 打开文件 */
    openfile(url, name, type) {
      window.open(url, "_blank");
      // let uploadType = url
      //   .slice(url.lastIndexOf("."), url.length)
      //   .toLowerCase();
      // let arr = [
      //   ".gif",
      //   ".png",
      //   ".jpeg",
      //   ".jpg",
      //   ".mp4",
      //   ".webm",
      //   ".pdf",
      //   ".wps",
      //   ".docx",
      //   ".doc",
      //   ".rtf",
      //   ".pptx",
      //   ".ppt",
      //   ".xls",
      //   ".xlsx",
      //   ".wps",
      //   ".ofd",
      //   ".txt",
      //   ".js",
      //   ".json",
      //   ".css",
      //   ".sql",
      //   ".xml",
      //   ".java",
      //   ".cs(c#)",
      // ];
      // if (type == "1") {
      //   this.isHttps = false;
      //   if (arr.indexOf(uploadType) > -1) {
      //     this.drawer = true;
      //     this.drawerurl = url;
      //     this.drawername = name;
      //     this.drawertype = type;
      //   } else {
      //     window.open(url, "_blank");
      //   }
      // } else {
      //   this.drawer = true;
      //   this.isHttps = true;
      //   this.drawerurl = url;
      //   this.drawername = name;
      //   this.drawertype = type;
      // }
    },
    /* 三维课件组件返回 (调用上传课件接口)*/
    add3DReturn(e) {
      e.contentTemporaryId = this.form.contentTemporaries[this.stepIndex].id;
      addPost_file(e).then((res) => {
        this.getFileList();
      });
    },

    /* 按钮来判断上传类型 并记录 */
    uploadType(type) {
      this.utype = type;
      //上传三维课件
      if (type == "上传三维课件") {
        this.add3DOpen = true;
      } else {
        this.$refs.fileInput.click();
      }
    },
    async uploadFile(event) {
      let files = event.target.files;
      let formData = new FormData();
      for (let i = 0; i < Array.from(files).length; i++) {
        if (
          Array.from(files)[i].name.substring(
            Array.from(files)[i].name.lastIndexOf(".") + 1
          ) == "ppt"
        ) {
          this.$modal.msgWarning("不支持上传ppt文件格式");
          return false;
        } else {
          formData.append(
            "files",
            new File([Array.from(files)[i]], Array.from(files)[i].name)
          );
        }
      }
      // Array.from(files).forEach((file) => {
      //   if (file.name.substring(file.name.lastIndexOf(".") + 1) == "ppt") {
      //     this.$modal.msgWarning("不支持上传ppt文件格式");
      //     return false;
      //   } else {
      //     formData.append("files", new File([file], file.name));
      //   }
      //   // const fileName = file.name.replace(/\.ppt$/, ".pptx");
      // });
      let path = "";
      path = fammterString(2, this.courseForm.dirName);
      let res = await uploadOSS(files, path, true, event);
      await Promise.all(
        res.map(async (item, index) => {
          await addPost_file({
            fileUrl: item.url,
            fileName: item.name,
            type: 1,
            contentTemporaryId: this.form.contentTemporaries[this.stepIndex].id,
          });
        })
      );
      event.target.value = "";
      this.$modal.msgSuccess("上传成功");
      this.getFileList();
    },
    /* 删除课件 */
    delCourseware(type, fileIndex) {
      this.$confirm(`确定删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 调用删除课件接口
          await delPost_file(
            this.form.contentTemporaries[this.stepIndex].taskFileTemporaries[
              fileIndex
            ].id
          ).then((res) => {
            this.form.contentTemporaries[
              this.stepIndex
            ].taskFileTemporaries.splice(fileIndex, 1);
          });
        })
        .catch(() => {});
    },
    /* 获取步骤信息 (分草稿和正式课程) */
    async getInfo() {
      this.loading = true;
      let res;
      if (this.$route.query.courseId) {
        res = await getPost_officalCourseTask(this.taskId);
      } else {
        res = await getPost_courseTask(this.taskId);
      }
      this.form = res.data;
      await this.getcontentTemporaries();
      this.loading = false;
      await this.getFileList();
    },
    /* 获取环节列表 (分草稿和正式课程)*/
    async getcontentTemporaries() {
      let res;
      if (this.$route.query.courseId) {
        res = await listPost_officalCourseTaskContent({
          taskId: this.taskId,
          pageSize: 999,
          pageNum: 1,
        });
      } else {
        res = await listPost_courseTaskContent({
          taskTemporaryId: this.taskId,
          pageSize: 999,
          pageNum: 1,
        });
      }

      this.form.contentTemporaries = [];
      if (res.rows && res.rows.length > 0) {
        for (const row of res.rows) {
          let obj = {
            ...row,
            showEdit: false,
          };
          this.form.contentTemporaries.push(obj);
        }
      }
      // 如果没有内容 则添加内容
      else {
        this.form.contentTemporaries = res.rows;
      }
      this.$forceUpdate();
      if (res.rows.length > 0) {
        this.$nextTick(() => {
          this.dragTab();
        });
      }
      console.log("获取环节列表", this.form.contentTemporaries);
    },
    /* 获取任务附件列表 */
    async getFileList() {
      console.log("获取任务附件列表");
      if (this.form.contentTemporaries.length > 0) {
        let res;
        if (this.$route.query.courseId) {
          res = await listPost_officalFile({
            contentId: this.form.contentTemporaries[this.stepIndex].contentId,
          });
        } else {
          res = await listPost_file({
            contentTemporaryId: this.form.contentTemporaries[this.stepIndex].id,
          });
        }
        console.log(this.form.contentTemporaries, "contentTemporaries");
        console.log(res.rows, "res.rows");
        this.form.contentTemporaries[this.stepIndex].taskFileTemporaries =
          res.rows;
        this.$forceUpdate();
      }
    },
    /* 添加教学内容 */
    async handleAddStep() {
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        if (this.form.contentTemporaries == null) {
          this.form.contentTemporaries = [];
        }
        let res = await addPost_courseTaskContent({
          taskFileTemporaries: [],
          description: "",
          contentName: "",
          contentUrl: "",
          taskTemporaryId: this.taskId,
        });
        this.form.contentTemporaries.push({
          id: res.data,
          taskTemporaryId: this.taskId,
          contentId: null,
          taskId: null,
          contentName: `内容${this.form.contentTemporaries.length + 1}`,
          description: "",
          contentUrl: "",
          showEdit: false,
          sort: this.form.contentTemporaries.length + 1,
          taskFileTemporaries: null,
        });
        if (this.sortArr.length > 0) {
          this.sortArr.push({
            id: res.data,
            taskTemporaryId: this.taskId,
            contentId: null,
            taskId: null,
            contentName: `内容${this.form.contentTemporaries.length + 1}`,
            description: "",
            contentUrl: "",
            showEdit: false,
            sort: this.form.contentTemporaries.length + 1,
            taskFileTemporaries: null,
          });
        }
        this.$forceUpdate();
        this.$nextTick(() => {
          this.stepIndex = this.form.contentTemporaries.length - 1 + "";
          this.dragTab();
          const navWrap = this.$refs.tabs.$el.querySelector(".el-tabs__nav");
          console.log((navWrap.scrollWidth - 755) * -1);
          if (navWrap.scrollWidth > 762)
            navWrap.style.transform = `translateX(${
              (navWrap.scrollWidth - 755) * -1 - 100
            }px)`;
          this.isLock = false;
        });
        setTimeout(() => {
          loading.close();
        }, 800);
      } catch (e) {
        loading.close();
      }
    },
    /* 删除教学内容 */
    handleTabsEdit(targetName, action) {
      for (const contentTemporary of this.form.contentTemporaries) {
        if (contentTemporary.showEdit) {
          return;
        }
      }
      this.$confirm(`确定删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(this.form.contentTemporaries, event, targetName, "111");
          let res = await delPost_courseTaskContent(
            this.form.contentTemporaries[targetName].id
          );
          if (res.code == 200) {
            this.form.contentTemporaries.splice(targetName, 1);
            this.$nextTick(() => {
              this.dragTab();
            });
          }
        })
        .catch(() => {});
    },
    /* 拖拽教学内容 */
    dragTab() {
      const tbody = document.querySelector(".stepbox_tabs .el-tabs__nav");

      if (tbody) {
        this.sortable = Sortable.create(tbody, {
          animation: 250,
          sort: true,
          handle: ".is-closable",
          onEnd: (/**Event*/ evt) => {
            if (evt.newIndex == evt.oldIndex) {
              return;
            }
            let arr = JSON.parse(
              JSON.stringify(
                this.sortArr.length > 0
                  ? this.sortArr
                  : this.form.contentTemporaries
              )
            );
            let oldIndex = evt.oldIndex;
            let newIndex = evt.newIndex;
            let element = arr[oldIndex];
            // 从旧位置删除元素
            arr.splice(oldIndex, 1);
            // 在新位置插入元素
            arr.splice(newIndex, 0, element);

            arr.map((item, index) => {
              item.sort = index + 1;
            });
            this.sortArr = arr;
            let ids = arr.map((item) => {
              return item.id;
            });
            sort_courseTaskContent(JSON.stringify(ids)).then((res) => {});
          },
        });
      }
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: undefined,
        taskName: undefined,
        describe: undefined,
        contentTemporaries: [],
      };
      this.resetForm("form");
    },
    async handleSubmitForm() {
      const loading = this.$loading({
        lock: true,
        text: "正在保存...",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      this.submitForm(this.form, loading);
      this.$modal.msgSuccess("保存成功");
    },
    // 修改步骤信息
    async submitForm(form, loading) {
      console.log(
        "修改步骤信息",
        form.contentTemporaries,
        this.queryParam.type
      );
      if (this.queryParam.type == "edit" || this.queryParam.type == "add") {
        if (form.contentTemporaries && form.contentTemporaries.length > 0) {
          //保存当前选中富文本内容
          let params = form.contentTemporaries[this.stepIndex];
          delete params.sort;
          let res = await updateContentTemporary(params);
        }
        //保存当前选中富文本内容end>>>>>>>>>>>
        let data = form;
        delete data.taskName;
        let sortedData = {
          ...data,
        };
        delete sortedData.contentTemporaries;
        try {
          let res = await updatePost_courseTask(sortedData);
          if (res && loading) {
            this.sortArr = [];
            loading.close();
          }
        } catch (e) {
          if (loading) {
            loading.close();
          }
        }
      }
    },
    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="scss">
.detailbottom {
  border-top: 1px solid #ebebeb;
  height: 72px;
  box-sizing: border-box;
  padding: 0 19px 0 37px;
  align-items: center;

  ::v-deep .el-button {
    padding: 0 24px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    border-radius: 8px;
    line-height: 38px;
    height: 40px;
  }

  .questionBtn {
    height: 32px;
    background: #fff0df;
    border-radius: 8px;
    align-items: center;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #f89a33;

    img {
      margin-right: 6px;
      width: 12px;
      height: 12px;
    }

    padding: 0 10px;
  }

  .examBtn:hover {
    .del {
      display: block;
    }
  }

  .examBtn {
    padding: 0 16px;
    margin-left: 16px;
    align-items: center;
    text-align: center;
    height: 32px;
    background: #e8fbff;
    border-radius: 8px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e8dff;

    .activeIcon {
      display: none;
    }

    .icon {
      display: none;
    }

    .del {
      display: none;
      width: 14px;
      height: 14px;
      top: -4px;
      right: -4px;
    }
  }

  .noExamBtn:hover {
    color: #28b28b;

    .activeIcon {
      display: block;
    }

    .icon {
      display: none;
    }
  }

  .noExamBtn {
    margin-left: 16px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    align-items: center;
    height: 32px;
    background: #f5f6f7;
    padding: 0 10px;

    .activeIcon {
      display: none;
      margin-right: 6px;
      width: 12px;
      height: 12px;
    }

    .icon {
      display: block;
      margin-right: 6px;
      width: 12px;
      height: 12px;
    }

    .del {
      display: none;
      width: 14px;
      height: 14px;
    }
  }
}

.lookDetail {
  width: 880px;
  padding: 24px 40px 24px 40px;
  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;

  .item {
    .item_lable {
      margin-right: 32px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 22px;
    }

    .item_value {
      width: 696px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 22px;
      white-space: pre-wrap;
    }
  }

  .steps {
    margin-top: 24px;

    // ::v-deep .el-tabs__nav-wrap {
    //   padding-left: 24px !important;
    // }

    .content {
      margin-top: 28px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 22px;
    }

    .fileTitle {
      margin-top: 40px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 22px;
    }

    .files {
      .files_file:nth-of-type(3n + 1) {
        margin: 24px 0 0 0;
      }

      .files_file {
        margin: 24px 0 0 98px;

        .icon {
          width: 32px;
          height: 32px;
          margin-right: 16px;
        }

        .filename {
          width: 149px;
          font-size: 16px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
          line-height: 32px;
        }
      }
    }
  }
}

.detail {
  padding-top: 32px;
  padding-bottom: 32px;
  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;
}

.description {
  margin-left: 48px;

  .lable {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 22px;
    margin: 0px 32px 0 0;
  }
}

.stepbox {
  .tabContent {
    padding: 20px 20px 20px 0;

    .addflie {
      width: 135px;
      margin-bottom: 10px;

      img {
        margin: auto 8px auto 0;
        width: 14px;
        height: 14px;
      }

      padding: 0 12px;
      height: 32px;
      border-radius: 8px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;
      line-height: 32px;
    }
  }

  &_title {
    margin-left: 48px;
    margin-top: 24px;
    height: 22px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 22px;
  }

  &_tip {
    margin: 4px 0 10px 10px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ea3555;
    line-height: 20px;
  }
}

.addStep {
  box-sizing: border-box;

  img {
    width: 20px;
    height: 20px;
    margin: auto 8px auto 0;
  }

  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #666666;
}

.card {
  .stepbox_tabs {
    width: 800px;
    margin-top: 35px;
    margin-left: 48px;
  }
  .stepbox_tabs,
  .lookDetail {
    ::v-deep .el-tabs__nav-wrap {
      padding-left: 0 !important;
    }
    ::v-deep .el-tabs__new-tab {
      display: none;
    }

    ::v-deep .el-tabs__item {
      height: 40px !important;
      line-height: 40px !important;
    }

    ::v-deep .el-tabs__item:last-child {
      height: 40px !important;
      line-height: 40px !important;
    }

    ::v-deep .el-tabs__header {
      margin: 0 0 0px 0;
    }
  }
}

.addflies {
  margin-bottom: 20px;
}

// 文件列表
.file:hover {
  background: rgba(204, 204, 204, 0.4);

  .del {
    display: block;
  }

  .name {
    color: rgba(39, 196, 120, 1);
  }

  .icon {
    display: none;
  }

  .iconactive {
    display: block;
  }
}

.file {
  width: 275px;
  height: 20px;

  .icon {
    display: block;
    margin: auto 3px auto 3px;
    width: 11px;
    height: 14px;
  }

  .iconactive {
    display: none;
    margin: auto 3px auto 3px;
    width: 11px;
    height: 14px;
  }

  .name {
    width: 240px;
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
    color: rgba(48, 49, 51, 1);
  }

  .del {
    margin: auto 0 auto 0;
    display: none;
    width: 10px;
    height: 10px;
  }
}

//富文本回显样式
::v-deep h5,
.h5 {
  font-size: 14px;
}

::v-deep h4,
.h4 {
  font-size: 16px;
  font-weight: bold;
}

::v-deep h3,
.h3 {
  font-size: 18px;
  font-weight: bold;
}

::v-deep h2,
.h2 {
  font-size: 20px;
  font-weight: bold;
}

::v-deep h1,
.h1 {
  font-size: 22px;
  font-weight: bold;
}
::v-deep i {
  font-style: italic;
}
::v-deep .w-e-toolbar .w-e-menu i {
  font-style: normal;
}
::v-deep ol {
  list-style-type: decimal;
}

/* ul ol 样式 */
::v-deep ol {
  margin: 10px 0 10px 22px;
  list-style-type: decimal;
}
::v-deep ul {
  margin: 10px 0 10px 22px;
  list-style-type: disc;
}
/* table 样式 */
::v-deep table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
::v-deep table td,
::v-deep table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
  height: 32px;
}
::v-deep table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
  background-color: #f1f1f1;
}

/* blockquote 样式 */
::v-deep blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  min-height: 24px;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
::v-deep code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
::v-deep pre code {
  display: block;
}
::v-deep a {
  text-decoration: underline;
  color: #5592e5;
}
.contentName {
  width: 100px;
}
</style>
